package zheng.mockit;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.MapConfiguration;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import sun.security.x509.IPAddressName;
import zheng.mockit.plugin.IPlugin;
import zheng.mockit.utils.JacksonUtils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * Created by zcz on 16-7-29.
 */
public abstract class AbstractMockitTestCase {

    protected MockitCore mockitCore = new MockitCore();

    @Before
    public void before() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Field[] fields = getClass().getDeclaredFields();
        for (Field field :fields) {
            Class pluginClazz = field.getType();
            PluginConf pluginConf = field.getAnnotation(PluginConf.class);
            if (pluginConf != null && IPlugin.class.isAssignableFrom(pluginClazz)) {
                Map confMap = JacksonUtils.jsonToBean(pluginConf.value(), Map.class);
                Configuration config = new MapConfiguration(confMap);
                IPlugin plugin = (IPlugin) pluginClazz.newInstance();
                plugin.setConf(config);
                plugin.setMessageHandler(mockitCore.getMessageHandler());
                field.setAccessible(true);
                field.set(this, plugin);
                mockitCore.addPlugin(plugin.getClass().getName(), plugin);
                plugin.startup();
            }
        }
    }

    @After
    public void after() {
        for (String key : mockitCore.getPluginMap().keySet()) {
            IPlugin plugin = mockitCore.getPluginMap().get(key);
            plugin.shutdown();
        }
    }

    @Test
    public void test() {
        runTC();
    }

    protected abstract void runTC();
}
